<template>
  <div>
    <h3>训练计划统计</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row type="flex" style="margin-bottom: 20px;" :gutter="10" justify="space-between">
            <el-col :span="6">
              <el-select @change="sportChange" v-model="searchForm.sportId" size="small" collapse-tags filterable clearable placeholder="选择运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select @change="sportItemChange" v-model="searchForm.sportItemId" size="small" collapse-tags filterable clearable placeholder="选择运动小项">
                <el-option :label="item" :value="key" v-for="(item,key,index) in sportItemData" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.empId" multiple size="small" collapse-tags filterable clearable placeholder="选择教练员">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in empData" :key="index"></el-option>
                </el-select>
                <el-button @click="searchForm.empId=Object.keys(empData)" size="small" type="primary">全选</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="6">
              <el-select v-model="searchForm.docClassId" size="small" collapse-tags filterable clearable placeholder="选择文档类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_docClass" :key="index"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row type="flex" :gutter="10">
            <el-col :span="6" style="display: flex;">
              <el-button type="success" icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="mini" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="6">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="center" unlink-panels style="width: 90%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="6" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="getStatistics"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="6">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row :expand-config="{labelField: 'expand', expandAll: true}"
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="empName" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="docClassName" title="训练方案类别" sortable></vxe-table-column>
        <vxe-table-column field="count" title="提交数量" sortable></vxe-table-column>
        <vxe-table-column type="expand" title="文档(展开/收起)" sortable width="150">
          <template #default="{ row, rowIndex  }">
            <a @click="$refs.XTable.toggleRowExpand(dataList[rowIndex])">共<span style="color: #0C9776;font-weight: bold;"> {{row.period?row.period.split(',').length:0}} </span>条记录</a>
          </template>
          <template #content="{ row }" class="expand">
            <el-link @click="planPreview(row,index)" style="margin: 5px 20px;" type="primary" v-for="item,index in row.period.split(',')" :key="index">{{ item }}</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <!-- 单个打印预览 -->
    <vxe-modal v-model="printModal" title="打印预览" height="800" show-zoom resize width="600" show-footer>
      <template #default>
        <weekPlanPrint v-if="currentDocClassId==33||currentDocClassId==34" id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
        <otherPlanPrint v-else  id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
      </template>
      <template #footer>
        <el-button @click="printPlan" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {get_sport_all,available4planStatistics,empId2sportInfo,all4planStatistics,by_sportId,pcm4emp} from '@/api/dict.js'
  import {plan_statistics,allType} from '@/api/plan.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  export default {
    components: {
      otherPlanPrint,
      weekPlanPrint,
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_sport: {},
        dict_docClass: {},
        dic_emp2sport: {},
        dict_docData: {},
        sportItemData: {},
        empData: {},
        searchForm: {
          sportId: '',
          sportItemId: '',
          empId: [],
          docClassId: '',
          openDate: '',
          closeDate: '',
        },
        printModal: false,
        currentDocClassId: '',
        previewData: {},
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getStatistics()
      })
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      printPlan() {
        const divEl = document.getElementById('myPrint')
        this.$XPrint({
          sheetName: '训练计划',
          content: divEl.innerHTML
        })
      },
      planPreview(row,index) {
        let docClassId = row.docClassId
        let docDataId = row.docDataIds.split(',')[index]
        allType({docClassId:docClassId,docDataId:docDataId}).then(res=>{
          if(res.code === 200) {
            this.currentDocClassId = docClassId
            this.previewData = res.data
            this.printModal = true
          }else{
            this.$message.error(res.message)
          }
        })
      },
      clearTableFilter() {
        this.searchForm = {
          sportId: '',
          sportItemId: '',
          empId: [],
          docClassId: '',
          openDate: '',
          closeDate: '',
        }
        this.doubleDate = ''
        this.getStatistics()
      },
      sportChange(val) {
        this.searchForm.sportItemId = ''
        this.sportItemData = {}
        by_sportId({sportId:val}).then(res=>{
          this.sportItemData = res
        })
        this.sportItemChange()
      },
      sportItemChange(val) {
        this.searchForm.empId = ''
        this.empData = {}
        pcm4emp({sportId:this.searchForm.sportId,sportItemId:this.searchForm.sportItemId}).then(res=>{
          this.empData = res
        })
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>训练计划统计</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '训练计划统计',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      getStatistics() {
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(this.searchForm.empId.length!=0) data.empId = this.searchForm.empId.join(',')
        if(this.searchForm.docClassId) data.docClassId = this.searchForm.docClassId
        if (this.doubleDate) {
          data.openDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.closeDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        plan_statistics(data).then(res=>{
          if(res.code === 200 && res.data.length!=0){
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.sport = this.dic_emp2sport[item.empId]
          if(item.docDataIds){
            let docDataIdsArr = item.docDataIds.split(',')
            let arr = []
            docDataIdsArr.forEach(docDataId=>{
              arr.push(this.dict_docData[docDataId])
            })
            item.period = arr.join(',')
          }else{
            item.period = ''
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          get_sport_all().then(res=>{
            this.dict_sport = res
          })
          available4planStatistics().then(res=>{
            this.dict_docClass = res
          })
          empId2sportInfo('sport').then(res=>{
            this.dic_emp2sport = res
          })
          all4planStatistics().then(res=>{
            this.dict_docData = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
          console.log(this.dataList)
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container{
  background-color: #FFFFFF;
  padding: 10px;
  .expand{
    display: flex;
    flex-wrap: wrap;
    .el-link{
      margin-right: 10px;
    }
  }
}
</style>
